package com.xunshibao.lucene;

import java.io.File;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

/**
 * Created by Eone Zhang
 * User: Administrator
 * Date: 11-3-27
 * Time: 下午4:10
 * To change this template use File | Settings | File Templates.
 */
public class Searcher {
    /**
     * 检索索引
     *
     * @param indexDir
     * @param q
     * @throws Exception
     */
    public void search(String indexDir, String q) throws Exception {
        // 打开索引
        Directory dir = FSDirectory.open(new File(indexDir));
        IndexSearcher is = new IndexSearcher(dir);

        // 创建查询对象解析器
        QueryParser parser = new QueryParser(Version.LUCENE_30, "contents", new StandardAnalyzer(Version.LUCENE_30));
        // 解析关键字
        Query query = parser.parse(q);
        //另外一种创建查询解析的方式
        Query query1 = new TermQuery(new Term("contents", q)); // TODO unused

        long start = System.currentTimeMillis();

        // 执行查询
        TopDocs hits = is.search(query, 10);
        long end = System.currentTimeMillis();
        // 获取查询到的文档
        for (ScoreDoc scoreDoc : hits.scoreDocs) {
            Document doc = is.doc(scoreDoc.doc); //取得结果
            System.out.println(doc.get("fullpath"));
        }
        // 关闭索引对象
        is.close();
    }
}
